package com.ita.os.merchant.web.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileUploadBase;

import com.ita.os.merchant.exception.UserExistException;
import com.ita.os.merchant.po.Merchant;
import com.ita.os.merchant.service.MerchantService;
import com.ita.os.merchant.service.impl.MerchantServiceImpl;
import com.ita.os.merchant.util.FileBean;
import com.ita.os.merchant.util.UploadTool;
import com.ita.os.merchant.util.WebUtils;
import com.ita.os.merchant.util.XmlResolverUtil;
import com.ita.os.merchant.web.formbean.RegisterFormBean;

/**
 * Servlet implementation class EditMerchantInfoServlet
 */
public class MerchantServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MerchantService merchantService = new MerchantServiceImpl();

	public MerchantServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String action = request.getParameter("action");
		if ("editInfo".equals(action)) {
			editInfo(request, response);
		} else if ("infoPreSave".equals(action)) {
			infoPreSave(request, response);
		}
	}

	private void infoPreSave(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setAttribute("mainPage", "editInfo.jsp");
		request.getRequestDispatcher("main.jsp").forward(request, response);
	}

	private void editInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String savePath = "d:/upload";
		String tempPath = "d:/temp";
		String message = "";
		try {
			UploadTool uploadTool = new UploadTool();
			uploadTool.setRequest(request);
			uploadTool.setSavePath(savePath);
			uploadTool.setTempPath(tempPath);
			uploadTool.uploadFiles();
			FileBean fileBean = new FileBean();
			Map<String,String> formDatas = uploadTool.getFormDatas();
			List<FileBean> fList = uploadTool.getFileBeanList();
			Merchant merchant = mapToMerchant(formDatas);
			merchant.setLogo(fList.get(0).getFilePath());
			XmlResolverUtil.init();
			XmlResolverUtil.sendXML(merchant);
			message = String.format(
                "恭喜：%s,提交审核！本页将在2秒后跳到首页！！<meta http-equiv='refresh' content='2;url=%s'", 
                merchant.getMname(),"index");
		} catch (FileUploadBase.FileSizeLimitExceededException e) {
			e.printStackTrace();
			request.setAttribute("message", "单个文件超出最大值！！！");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
			return;
		} catch (FileUploadBase.SizeLimitExceededException e) {
			e.printStackTrace();
			request.setAttribute("message", "上传文件的总的大小超出限制的最大值！！！");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
			return;
		} catch (Exception e) {
			message = "文件上传失败！";
			e.printStackTrace();
		}
		request.setAttribute("message", message);
		request.getRequestDispatcher("/message.jsp").forward(request, response);

	}

	private void register(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		RegisterFormBean formbean = WebUtils.request2Bean(request, RegisterFormBean.class);
		if (formbean.validate() == false) {
			request.setAttribute("formbean", formbean);
			request.getRequestDispatcher("/WEB-INF/pages/register.jsp").forward(request, response);
			return;
		}

		Merchant merchant = new Merchant();
		try {
			BeanUtils.copyProperties(merchant, formbean);
			merchantService.addMerchant(merchant);
			String message = String.format("注册成功！！3秒后为您自动跳到登录页面！！<meta http-equiv='refresh' content='3;url=%s'/>",
					request.getContextPath() + "/loginUi");
			request.setAttribute("message", message);
			request.getRequestDispatcher("/message.jsp").forward(request, response);
		} catch (UserExistException e) {
			formbean.getErrors().put("userName", "注册用户已存在！！");
			request.setAttribute("formbean", formbean);
			request.getRequestDispatcher("/WEB-INF/pages/register.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("message", "对不起，注册失败！！");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
		}

	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Merchant merchant = merchantService.findMerchant(username, password);
		if (merchant == null) {
			String message = String.format(
					"对不起，用户名或密码有误！！请重新登录！2秒后为您自动跳到登录页面！！<meta http-equiv='refresh' content='2;url=%s'",
					request.getContextPath() + "/loginUi");
			request.setAttribute("message", message);
			request.getRequestDispatcher("/message.jsp").forward(request, response);
			return;
		}
		request.getSession().setAttribute("merchant", merchant);
		String message = String.format("恭喜：%s,登陆成功！本页将在3秒后跳到首页！！<meta http-equiv='refresh' content='2;url=%s'",
				merchant.getMname(), "index");
		request.setAttribute("message", message);
		request.getRequestDispatcher("/message.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private Merchant mapToMerchant(Map<String,String> map){
		Merchant merchant = new Merchant();
		for(String key : map.keySet()){
			switch(key){
			case "mid":
				merchant.setMid(Integer.valueOf(map.get(key)));
				break;
			case "mname":
				merchant.setMname(map.get(key));
				break;
			case "type":
				merchant.setType(map.get(key));
				break;
			case "address":
				merchant.setAddress(map.get(key));
				break;
			case "tel":
				merchant.setTel(map.get(key));
				break;
			case "info":
				merchant.setInfo(map.get(key));
				break;
			case "email":
				merchant.setEmail(map.get(key));
				break;
			case "password":
				merchant.setPassword(map.get(key));
				break;
			}
		}
		return merchant;
	}
}